package com.itheima.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 * 能不查数据库就不查，减少数据库压力
 */
//如果使用@ConrtollerAdvice注解的话，方法体要加@Requestbody 否则会报错
// 如果使用@RestControllerAdvice 注解 方法体不需要加@RequestBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody

@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        //违反username唯一约束的异常（重复username，SQL抛出的异常
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");//根据空格分隔，拿到数组对象
            String msg = "账号"+split[2] + "已存在";//数组的第三个元素（0,1,2）就是重复的username数值
            return R.error(msg);
        }

        return R.error("未知错误");
    }


    /**
     * 业务异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }

}
